package com.example.sachon;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;

import com.example.sachon.vo.ChonInfo;

public class SA0200 extends Activity {
	
	public static  final int SERVER_MODE_LOAD_CHON_INFO = 1;
	private  static final String SERVER_CHON_LIST_URL = Const.SERVER_BASE_URL+"chon_list.jsp";
	private ProgressDialog progressbar;	
	
	private int server_mode;
	private ArrayList<ChonInfo> _array_chon;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sa0200);
        
        setTitle("마을선택");
        readServer_chon_list();
        
    }
    private void init_chon_tile(){
    	GridView gridview = (GridView) findViewById(R.id.gridview);
    	
    	ChonTileAdapter tileAdapter = new ChonTileAdapter(_array_chon, R.layout.activity_chon_tile_context, this);
    	 
        gridview.setAdapter(tileAdapter);
        
 
        gridview.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView parent, View v, int position, long id) {
               // Toast.makeText(SA0200.this, "" + position, Toast.LENGTH_SHORT).show();
            	ChonInfo ci  =  _array_chon.get(position);
            	
            	Const.getInstance().chonInfo().setChon_id(ci.getChon_id());
            	Const.getInstance().chonInfo().setChon_nm(ci.getChon_nm());
            	Const.getInstance().chonInfo().setChon_small_img(ci.getChon_small_img());
            	
				Intent intent = new Intent();
				intent.setClass(SA0200.this, SA0300.class);
								
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
				startActivity(intent);
            }
        });
    	
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }
    /**
     *     마을정보 리스트 불러오기 
     */
    	private void readServer_chon_list() {
    		Thread thread = new Thread(new Runnable() {
    			public void run() {
    					
    				try {
    					server_mode = SERVER_MODE_LOAD_CHON_INFO;
    					
    					String postURL = SERVER_CHON_LIST_URL;// Const.SERVER_BASE_URL+"chon_list.jsp";
    					HttpPost post = new HttpPost(postURL);

    					List<NameValuePair> params = new ArrayList<NameValuePair>();

    					post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
    					HttpResponse responsePOST = new DefaultHttpClient().execute(post);
    					HttpEntity resEntity = responsePOST.getEntity();

    					if (resEntity != null) {
    						String responseString = EntityUtils.toString(resEntity, "UTF-8");
    							
    						System.out.println("ListActivity : " + responseString.trim());
    						
    						if(responseString.trim().equals("[\"no data\"]")) {
    							mHandler.sendEmptyMessage(200);
    						} else {
    					    	
    					    	_array_chon = new ArrayList<ChonInfo>();

    							JSONArray jsonArray = new JSONArray(responseString.trim());
    							for (int i = 0; i < jsonArray.length(); i++) {
    								JSONObject jsonObject = jsonArray.getJSONObject(i);
    								ChonInfo listItem = new ChonInfo();
    								
    								listItem.setChon_id(jsonObject.getString("chon_id"));
    								listItem.setChon_nm(jsonObject.getString("chon_nm"));
    								listItem.setChon_small_img(jsonObject.getString("chon_small_img"));
     
    								_array_chon.add(listItem);
    							}
    							
    							mHandler.sendEmptyMessage(100);
    						}
    					}
    				} catch (Exception e) {
    					// TODO Auto-generated catch block
    					System.out.println(e.toString() );
    					mHandler.sendEmptyMessage(-100);
    				}
    			}
    		});

    		thread.start();
    		progressbar = ProgressDialog.show(this, null, "    Loading........");
    	}   
    	
    	private Handler mHandler = new Handler() {
    		public void handleMessage(Message msg) {
    				
    			progressbar.cancel();
    			
    			if (msg.what == 100) {
    				//Intent intent = new Intent();
    				//setResult(RESULT_OK, intent);
    				System.out.println("server_mode:"+server_mode);
    				switch (server_mode){
    					case SA0100.SERVER_MODE_LOAD_CHON_INFO:
    						init_chon_tile();
    						break;
   
    				}

    				
    				
    			} else if (msg.what == -100) {
    				Toast.makeText(SA0200.this, "처리중 오류발생", Toast.LENGTH_LONG).show();
    			}
    		}
    	};    	
}
